<template>
  <div>
    <div class="explain">
      <h4 style="margin-left: 1%;">操作说明:</h4>
      <p class="explain_p">
        *
        该功能主要用于学生的查询,添加 !
      </p>
    </div>
    <div class="top">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item style="margin-left: 1%;">
          <el-input v-model="formInline.name" placeholder="请输入学生姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.number" placeholder="请输入学生学号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.project_name" placeholder="所属项目">
            <el-option v-for="(i,index) in arr " :key="index" 
              :label="i.name" :value="i.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.class_name" placeholder="所属班级">
            <el-option v-for="(i,index) in arrclass" :key="index"
             :label="i.class_name" :value="i.class_name"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>

        <el-form-item>
          <el-upload
            ref="upload"
            action="/"
            :show-file-list="false"
            :on-change="importExcel"
            :auto-upload="false">
            <el-button
              slot="trigger"
              icon="el-icon-upload"
              size="small"
              type="primary">
              上传文件
            </el-button>
          </el-upload>
        </el-form-item>

        <el-button
          type="primary"
          id="ad"
          icon="el-icon-circle-plus-outline"
          @click="dialogVisible = true"
        >添加</el-button>        
      </el-form>
    </div>
<!-- 上下分级 -->
    <div style="overflow: hidden; margin-top: 1%">
      <el-table
        :data="tableData"
        id="tabb"
        border
        stripe
        v-loading="loading"
        style="width: 99%"
      >
        <el-table-column prop="id" label="序号" width="70"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column prop="number" label="学号" width="100"></el-table-column>
        <el-table-column prop="sex" label="性别" width="50"></el-table-column>
        <el-table-column
          prop="class_name"
          label="所属班级"
          width="200"
        ></el-table-column>        
        <el-table-column
          prop="phone"
          label="移动电话"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="address"
          label="家庭住址"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="idcard"
          label="身份证号"
          width="190"
        ></el-table-column>
        <el-table-column
          prop="project_name"
          label="所属项目"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="state"
          label="状态"
          width="100"
        >
          <el-switch
            v-model="zhuangtai"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-table-column>
        <el-table-column
          style="text-align: center"
          prop="operation"
          label="操作"
          width="150">
          <el-button @click="drawer = true" size="mini" type="primary">
            编辑
          </el-button>
          <el-button size="mini" type="danger">删除</el-button>
        </el-table-column>
      </el-table>
<!-- 上下分级 -->
      <el-dialog
        title="添加学生"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="学生姓名" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="所属项目">
            <el-select v-model="ruleForm.project_name" placeholder="请选择项目">
              <el-option v-for="(i,index) in arr " :key="index" 
                :label="i.name" :value="i.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属班级">
            <el-select v-model="ruleForm.class_name" placeholder="请选择班级">
              <el-option v-for="(i,index) in arrclass" :key="index"
              :label="i.class_name" :value="i.class_name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="ruleForm.sex" placeholder="男">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="身份证号" prop="idcard">
            <el-input v-model="ruleForm.idcard"></el-input>
          </el-form-item>
          <el-form-item label="家庭住址" prop="address">
            <el-input v-model="ruleForm.address"></el-input>
          </el-form-item>
          <el-form-item label="移动电话" prop="phone">
            <el-input v-model="ruleForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="学生状态" prop="state">
            <el-select v-model="ruleForm.state" placeholder="有效">
              <el-option label="有效" value="1"></el-option>
              <el-option label="无效" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确认</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
export default {
  data() {
    const generateData = () => {
      const data = [];
      for (let i = 1; i <= 15; i++) {
        data.push({
          key: i,
          label: `备选项 ${i}`,
          disabled: i % 4 === 0,
        });
      }
      return data;
    };
    return {
      data: generateData(),      
      // 后台返回的项目
      arr:{},
      // 后台返回的班级
      arrclass:{},
      // xlsx表格数据
      xlsxJson:[],
      //学生查询,
      formInline: {
        user: '',
        number:'',
        // 项目
        project_name: '',
        // 班级
        class_name:'',
      },
      // 状态
      zhuangtai: true,
      input: "",
      // loading:true, loading加载
      dialogVisible: false,
      drawer: false,
      // 显示列表
      tableData: [],
      // 添加
      ruleForm: {
        name:"",
        project_name:"",
        class_name:"",
        sex:"",
        phone:"",
        idcard:"",
        state:"",
        address:"",
      },
      rules: {
        number: [
          { required: true, message: "请输入用户账号", trigger: "blur" },
          { min: 3, max: 9, message: "长度在 3 到 9 个字符", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入用户姓名", trigger: "blur" }],
        role: [{ required: true, message: "请选择用户角色", trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        project: [
          { required: true, message: "请选择所属项目", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 添加数据
          const arr = this.ruleForm
          this.$http.post(`/api/createstudent`,arr).then((res) => {
            console.log(res.data)
            this.tableData = res.data
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
// 请求项目
    getstudent() {
      this.$http.get("/api/getstudent").then((res) => {
        console.log(res.data);
        this.arr = res.data
        console.log(this.arr);
      });
    },
// 请求班级
    outclasss(newValue) {
      this.$http.get(`/api/outclass?project=`+ newValue).then((res) => {
        this.arrclass = res.data
      });
    },
// 查询学生
    onSubmit(){
      const formInline = {}
      for(let i in this.formInline){
        if(this.formInline[i]!=null&&this.formInline[i]!=undefined&&this.formInline[i]!=''){
          formInline[i]=this.formInline[i];
        }
      }
      const _ = this.$http
      _.post(`/api/posttudent`,formInline).then((res) => {
        console.log(res.data)
        this.tableData = res.data
      });
    },
// 上传文件
    importExcel(file){
      const types = file.name.split('.')[1] // 分割
      const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => item === types)
      if (!fileType) { //判断上传的文件后缀 
        alert('格式错误！请重新选择')
        return
      }
      this.file2Xce(file).then(tabJson => { // 调用file2Xce
        if (tabJson && tabJson.length > 0) {
          this.xlsxJson = tabJson
          console.log(this.xlsxJson)
          // xlsxJson是解析出来的json数据
          // [
          //   {
          //     sheetName: sheet1
          //     sheet: sheetData
          //   }
          // ]
        }
      })
    },
    file2Xce(file) {
      // 返回一个Promise构造函数
      return new Promise(function(resolve, reject) {
        // Promise的构造函数接收一个参数，是函数，并且传入两个参数：resolve，reject
        // 姑且理解为一个成功，一个失败  
       console.log(reject)
        const reader = new FileReader() //FileReader 好像也是个函数
        reader.onload = function(e) { // FileReader异步回调函数onload 回调
          const data = e.target.result
          this.wb = XLSX.read(data, {
            type: 'binary'
          })
          const result = []
          this.wb.SheetNames.forEach((sheetName) => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            })
          })
          resolve(result)
        }
        reader.readAsBinaryString(file.raw)
        // reader.readAsBinaryString(file) // 传统input方法
      })
    }
  },
// 监听
    watch:{
      'formInline.project_name'(newValue){
        this.outclasss(newValue)
      },
      'ruleForm.project_name'(newValue){
        this.outclasss(newValue)
      }
    },
    created() {
      this.getstudent()
    },
};
</script>

<style scoped>
.cell {
  text-align: center;
}
.seach {
  width: 300px;
}
.top {
  margin-top: 15px;
  
}
.explain_p{
  margin-left: 1%;
  font-size: 12px;
}
.explain {
  border-radius: 15px;
  line-height: 30px;
  background-color: rgb(212, 306, 301);
  margin-top: 15px;
  margin-left: 4%;
}
#tabb {
  margin-left: 1%;
  border-radius: 15px;
}
#seac {
  margin-left: 20px;
}
#ad {
  float: right;
  margin-right: 4%;
}
</style>